import { values } from 'lodash'
import { I18nContext } from 'nestjs-i18n'
import { formatI18nValidationErrors } from '@libs/lhy-common'
import { HttpStatus, ValidationError } from '@nestjs/common'
import { CoreExceptionCode } from './core-exception-code'
import { CoreHttpException } from './core-http.exception'

/**
 * 用于validation校验异常
 */
export class CoreValidationException extends CoreHttpException {
  constructor(protected errors: ValidationError[]) {
    super(errors.map(error => values(error.constraints)).flat(1), {
      code: CoreExceptionCode.ValidationError,
      status: HttpStatus.BAD_REQUEST,
    })
  }

  getI18nError() {
    const i18n = I18nContext.current()
    const errors = formatI18nValidationErrors(this.errors ?? [], i18n?.service, { lang: i18n?.lang })
    return new CoreHttpException(errors.map(error => values(error.constraints)).flat(1), {
      code: this.code,
      status: this.getStatus(),
    })
  }
}
